package com.beilang.base.filter;


import org.springframework.context.ApplicationContext;
import static org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    protected ApplicationContext ctx;
    private static final String LOGIN_APPLIED = "LOGIN_APPLIED";

    /**
     * init method
     *
     * @param filterConfig
     * @throws ServletException
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        ctx = getRequiredWebApplicationContext(filterConfig.getServletContext());
    }

    /**
     * use this method to check is user need login,do the login actin if yes, otherwise forward to next filter
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        doFilterHttp((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse, filterChain);
    }

    private void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (request.getAttribute(LOGIN_APPLIED) != null ) {
            chain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("user") == null) {
            if(request.getRequestURI().indexOf("/flex/hotline.html")==-1)
                response.sendRedirect("/hotline/flex/hotline.html");
        }
        request.setAttribute(LOGIN_APPLIED, Boolean.TRUE);
        chain.doFilter(request, response);
        request.removeAttribute(LOGIN_APPLIED);
    }

    public final void destroy() {
    }

}

